package com.tanhua.server.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.server.service.CommentService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class CommentServiceImpl implements CommentService {
    @DubboReference
    private CommentApi commentApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public void postComments(String movementId, String comment) {
        //获取操作用户的ID
        Long id = UserHolder.getUserId();
        //构造comment
        Comment comment1 = new Comment();
        comment1.setPublishId(new ObjectId(movementId));
        comment1.setCommentType(CommentType.COMMENT.getType());
        comment1.setContent(comment);
        comment1.setUserId(id);
        comment1.setCreated(System.currentTimeMillis());
        //调用API保存评论
        Integer commentCount = commentApi.save(comment1);
        log.info("commentCount:" + commentCount);
    }

    /**
     * 查询动态的所有文字评论
     * @param movementId
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public PageResult movementList(String movementId, Integer page, Integer pagesize) {
        List<Comment> comments = commentApi.findComment(movementId, CommentType.COMMENT, page, pagesize);
        if (CollUtil.isEmpty(comments)) {
            return new PageResult();
        }
        List<Long> userIds = CollUtil.getFieldValues(comments, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        List<CommentVo> voList = new ArrayList<>();
        for (Comment comment1 : comments) {
            UserInfo userInfo = map.get(comment1.getUserId());
            if (userInfo != null) {
                CommentVo vo = CommentVo.init(userInfo, comment1);
                //判断该条评论是否被当前登录用户点过赞
                String key = Constants.MOVEMENTS_INTERACT_KEY + UserHolder.getUserId();
                String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + comment1.getId().toHexString();
                if (redisTemplate.opsForHash().hasKey(key,hashKey)){
                    vo.setHasLiked(1);
                }
                voList.add(vo);
            }
        }
        return new PageResult(page, pagesize, 0L, voList);
    }

    /**
     * 动态点赞
     *
     * @param id：动态的id
     * @return
     */
    @Override
    public Integer likeMovement(String id) {
        //1.调用api查询用户是否已经点过赞（可以从MongoDB中查询，也可以从Redis中查询）
        //三个参数，id表示动态的id，第二个参数表示当前操作人的id，第三个表示评论的类型是喜欢，也就是点赞
        Boolean hasComment = commentApi.hasComment(id, UserHolder.getUserId(), CommentType.LIKE);
        //2.如果已经点赞，抛出异常
        if (hasComment) {
            throw new BusinessException(ErrorResult.likeError());
        }
        //3.如果未点赞，保存数据到MongoDB
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(id));
        comment.setUserId(UserHolder.getUserId());
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setCreated(System.currentTimeMillis());
        Integer count = commentApi.save(comment);
        //4.拼接Redis的key，将点赞的状态存入Redis
        String key = Constants.MOVEMENTS_INTERACT_KEY + id;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().put(key, hashKey, "1");
        return count;
    }

    /**
     * 取消点赞
     *
     * @param id
     * @return
     */
    @Override
    public Integer dislikeMovement(String id) {
        Boolean hasComment = commentApi.hasComment(id, UserHolder.getUserId(), CommentType.LIKE);
        //如果未点赞，抛出异常
        if (!hasComment) {
            throw new BusinessException(ErrorResult.disLikeError());
        }
        //如果点赞，调用api删除数据，返回数据删除后的点赞数量
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(id));
        comment.setUserId(UserHolder.getUserId());
        comment.setCommentType(CommentType.LIKE.getType());
        Integer count = commentApi.remove(comment);
        //拼接Redis的key，删除点赞状态
        String key = Constants.MOVEMENTS_INTERACT_KEY + id;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key, hashKey);
        return count;
    }

    /**
     * 动态：特别喜欢
     *
     * @param id
     * @return
     */
    @Override
    public Integer loveMovement(String id) {
        //1.调用api查询用户是否已经点过赞（可以从MongoDB中查询，也可以从Redis中查询）
        //三个参数，id表示动态的id，第二个参数表示当前操作人的id，第三个表示评论的类型是喜欢，也就是点赞
        Boolean hasComment = commentApi.hasComment(id, UserHolder.getUserId(), CommentType.LOVE);
        //2.如果已经点赞，抛出异常
        if (hasComment) {
            throw new BusinessException(ErrorResult.loveError());
        }
        //3.如果未点赞，保存数据到MongoDB
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(id));
        comment.setUserId(UserHolder.getUserId());
        comment.setCommentType(CommentType.LOVE.getType());
        comment.setCreated(System.currentTimeMillis());
        Integer count = commentApi.save(comment);
        //4.拼接Redis的key，将点赞的状态存入Redis
        String key = Constants.MOVEMENTS_INTERACT_KEY + id;
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().put(key, hashKey, "1");
        return count;
    }

    @Override
    public Integer unloveMovement(String id) {
        Boolean hasComment = commentApi.hasComment(id, UserHolder.getUserId(), CommentType.LOVE);
        //如果未点赞，抛出异常
        if (!hasComment) {
            throw new BusinessException(ErrorResult.disloveError());
        }
        //如果点赞，调用api删除数据，返回数据删除后的点赞数量
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(id));
        comment.setUserId(UserHolder.getUserId());
        comment.setCommentType(CommentType.LOVE.getType());
        Integer count = commentApi.remove(comment);
        //拼接Redis的key，删除点赞状态
        String key = Constants.MOVEMENTS_INTERACT_KEY + id;
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key, hashKey);
        return count;
    }

    /**
     * 点赞别人的评论
     *  点赞完成后将用户id 和 被点赞的评论的id 作为key 和 hashkey 存入Redis中，类型为hash
     * @param commentId
     * @return
     */
    @Override
    public Integer likeComment(String commentId) {
        String key = Constants.MOVEMENTS_INTERACT_KEY + UserHolder.getUserId();
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + commentId;
        String flag = (String) redisTemplate.opsForHash().get(key, hashKey);
        if ("alreadyLike".equals(flag)){
            throw new BusinessException(ErrorResult.likeError());
        }
        Integer count = commentApi.likeComment(commentId);
        redisTemplate.opsForHash().put(key,hashKey,"alreadyLike");
        return count;
    }

    /**
     * 评论取消点赞
     * 取消完后后，删除Redis中对应的key和hashkey
     * @param commentId
     * @return
     */
    @Override
    public Integer dislikeComment(String commentId) {
        String key = Constants.MOVEMENTS_INTERACT_KEY + UserHolder.getUserId();
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + commentId;
        String flag = (String) redisTemplate.opsForHash().get(key, hashKey);
        if (!"alreadyLike".equals(flag)){
            throw new BusinessException(ErrorResult.disLikeError());
        }
        Integer count = commentApi.dislikeComment(commentId);
        redisTemplate.opsForHash().delete(key,hashKey);
        return count;
    }
}

